package com.leetcode.algorithm.y22.m06;

/**
 * 63. 不同路径 II
 * 
 * https://leetcode.cn/problems/unique-paths-ii/
 * 
 * @author jie.deng
 *
 */
class Question0063Solution01 {

	public int uniquePathsWithObstacles(int[][] obstacleGrid) {
		int m = obstacleGrid.length;
		int n = obstacleGrid[0].length;
		// DP状态定义
		int[][] dp = new int[m][n];

		// 初始化
		dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
		for (int i = 1; i < m; i++) {
			dp[i][0] = obstacleGrid[i][0] == 1 ? 0 : dp[i - 1][0];
		}
		for (int j = 1; j < n; j++) {
			dp[0][j] = obstacleGrid[0][j] == 1 ? 0 : dp[0][j - 1];
		}

		// 状态转移方程
		for (int i = 1; i < m; i++) {
			for (int j = 1; j < n; j++) {
				dp[i][j] = obstacleGrid[i][0] == 1 ? 0 : (dp[i - 1][j] + dp[i][j - 1]);
			}
		}

		return dp[m - 1][n - 1];
	}

}